package groupId.moxie;

import groupId.api.CarrierApi;
import groupId.api.MoxieApiFactory;
import groupId.api.ObjectMappers;
import groupId.task.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import retrofit2.Response;

import java.io.IOException;

/**
 * Desc:
 * Author:liubo
 * Date: 2017-07-05 11:35
 **/
@RestController
@RequestMapping("/auth")
public class MoxieController {

    @Autowired
    @Qualifier("moxieApiFactory")
    private MoxieApiFactory moxieApiFactory;

    @Autowired
    @Qualifier("carrierApi")
    private CarrierApi carrierApi;

    private static final Logger log = LoggerFactory.getLogger(MoxieController.class);

    @RequestMapping("/mobile")
    public String moxie() throws IOException {
        // 获取用户信息 用户名，身份证号
        TaskCreateReq req = TaskCreateReq.builder()
                .add(ParamName.USER_ID, "1111")
                .add(ParamName.ACCOUNT, "17756093143")
                .add(ParamName.PASSWORD, "810622")
                .add(ParamName.ORIGIN, "2")
                .add(ParamName.REAL_NAME, "刘波")
                .add(ParamName.ID_CARD, "34011119831215755X")
                .build();

        String taskId;
        Response<TaskCreateRsp> taskCreateRspResponse = carrierApi.createTask(req).execute();


        if (taskCreateRspResponse.isSuccessful()) {
            TaskCreateRsp taskCreateRsp = taskCreateRspResponse.body();
            taskId = taskCreateRsp.getTaskId();
            System.out.println("任务创建成功. taskId: " + taskId);
        } else {
            System.out.println("任务创建失败");
            System.out.println("status:" + taskCreateRspResponse.code());
            System.out.println(taskCreateRspResponse.errorBody().string());
            return "";
        }

        boolean isTaskDone = false;
        //Step2 轮询状态
        long pollEndTime = System.currentTimeMillis() + 180 * 1000; //轮询最多3分钟
        while (true) {
            Response<TaskStatusRsp> taskStatusRspResponse = carrierApi.getTaskStatus(taskId).execute();
            if (taskStatusRspResponse.isSuccessful()) {
                TaskStatusRsp taskStatusRsp = taskStatusRspResponse.body();
                String description = taskStatusRsp.getDescription();
                String phase = taskStatusRsp.getPhase();
                String phaseStatus = taskStatusRsp.getPhaseStatus();

                System.out.println(String.format("%s [%s] - %s", phase, phaseStatus, description));

                if (phaseStatus.equals("DOING")) {
                    System.out.println("任务正在执行");
                }

                if (phaseStatus.equals("DONE_SUCC")) {
                    System.out.println("任务已完成");
                    isTaskDone = true;
                    break;
                }

                if (phaseStatus.equals("DONE_FAIL") || phaseStatus.equals("DONE_TIMEOUT")) {
                    System.out.println("任务失败/超时");
                    return "任务失败/超时";
                }

                if (phaseStatus.equals("WAIT_CODE")) {
                    String inputType = taskStatusRsp.getInput().getType();
                    System.out.println("等待用户输入,类型:" + inputType);
                    if (taskStatusRsp.getInput().getType().equalsIgnoreCase("img")) {
                        System.out.println("base64在线转图片,访问 http://codebeautify.org/base64-to-image-converter");
                        System.out.println("请识别图片验证码:" + taskStatusRsp.getInput().getValue());
                        return "请输入图片验证码";
                    }
                    return "请输入手机验证码";
                }
            } else {
                System.out.println("任务状态查询失败");
                int statusCode = taskCreateRspResponse.code();
                System.out.println("status:" + statusCode + "\n");
                System.out.println(taskCreateRspResponse.errorBody().string() + "\n");
            }
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (System.currentTimeMillis() > pollEndTime) break;
        }

        if (isTaskDone) {
            System.out.println("恭喜! 现在可以查数据了");
        }


        return "";
    }

    @RequestMapping("/data")
    public String queryData(@RequestParam String mobile, @RequestParam String taskId, @RequestParam String smsCode) throws IOException {
        UserInput input = new UserInput(smsCode);
        Response<TaskVoidRsp> response = carrierApi.input(taskId, input).execute();

        System.out.println(response.body().getValue());
        Response<Object> mxData = carrierApi.getMxData(mobile, taskId).execute();

        System.out.println("mxData.class=" + mxData.getClass());
        System.out.println("mxData.body.class=" + mxData.body().getClass());


        mobile="17785246520";
        String idCard="340111198312157554";
        String name="厉害";
        Response<Object> mxReport = carrierApi.getReportBasic(mobile,name,idCard,taskId,null).execute();
        if(!mxReport.isSuccessful()){
            System.out.println("mxReport="+mxReport.errorBody().string());
        }
        String t=ObjectMappers.getObjectMapper().writeValueAsString(mxData.body());
        System.out.println("*******************json开始");
        System.out.println(t);
        System.out.println("*********json结束");
        int num = t.getBytes("utf-8").length;
        System.out.println("num="+num);
        System.out.println("mxReport.class=" + mxReport.getClass());
        System.out.println("mxReport.body.class=" + mxReport.body().getClass());
        String s=ObjectMappers.getObjectMapper().writeValueAsString(mxReport.body());
        System.out.println("*******************json开始");
        System.out.println(s);
        System.out.println("*********json结束");
        int num2 = s.getBytes("utf-8").length;
        System.out.println("num2="+num2);
//        String s = (String) mxData.body();
//        System.out.println("s="+s);
        return "";
    }

}
